<template>
  <div class="book-manage-wrap">
    <!-- 顶部标题栏 -->
    <div class="book-header">
      <div class="header-inner">
        <h1 class="header-title">图书管理模块</h1>
        <p class="header-desc">图书信息查询与库存管理</p>
      </div>
    </div>

    <!-- 核心功能区：搜索+新增 -->
    <div class="book-operation">
      <div class="operation-card">
        <!-- 搜索表单区 -->
        <div class="search-area">
          <el-form :model="searchForm" class="search-form" inline>
            <el-form-item label="图书标题" class="form-item">
              <el-input 
                v-model="searchForm.title" 
                placeholder="请输入标题关键字"
                class="search-input"
                prefix-icon="el-icon-search"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="图书分类" class="form-item">
              <el-input 
                v-model="searchForm.category" 
                placeholder="请输入分类"
                class="search-input"
                prefix-icon="el-icon-tags"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item class="form-btn-group">
              <el-button 
                type="primary" 
                icon="el-icon-search" 
                @click="searchBooks"
                class="search-btn">
                查询
              </el-button>
              <el-button 
                icon="el-icon-refresh-left" 
                @click="resetSearch"
                class="reset-btn">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 新增按钮区 -->
        <div class="add-btn-area">
          <el-button 
            type="success" 
            icon="el-icon-plus" 
            @click="openAddDialog"
            class="add-btn">
            添加图书
          </el-button>
        </div>
      </div>
    </div>

    <!-- 表格展示区 -->
    <div class="book-table">
      <div class="table-card">
        <!-- 表格数据统计 -->
        <div class="table-header">
          <div class="table-count">
            共 <span class="count-num">{{ tableData.length }}</span> 本图书
          </div>
        </div>
        <!-- 表格主体 -->
        <el-table
          :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)"
          border
          style="width: 100%"
          height="550"
          highlight-current-row
          :row-class-name="tableRowClass"
          :header-cell-style="tableHeaderStyle"
          :cell-style="tableCellStyle">
          <el-table-column 
            prop="id" 
            label="图书ID" 
            width="100" 
            align="center">
          </el-table-column>
          <el-table-column 
            prop="title" 
            label="图书标题" 
            width="220" 
            align="center">
            <template #default="scope">
              <div class="book-title" :title="scope.row.title">
                {{ scope.row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column 
            prop="author" 
            label="作者" 
            width="160" 
            align="center">
          </el-table-column>
          <el-table-column 
            prop="isbn" 
            label="ISBN" 
            width="200" 
            align="center">
          </el-table-column>
          <el-table-column 
            prop="category" 
            label="分类" 
            width="160" 
            align="center">
            <template #default="scope">
              <el-tag :type="getTagType(scope.row.category)" class="category-tag">
                {{ scope.row.category }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column 
            prop="stock" 
            label="库存数量" 
            width="140" 
            align="center">
            <template #default="scope">
              <div :class="scope.row.stock <= 0 ? 'stock-out' : 'stock-normal'">
                {{ scope.row.stock <= 0 ? '缺货' : scope.row.stock }}
              </div>
            </template>
          </el-table-column>
          <el-table-column 
            prop="createTime" 
            label="创建时间" 
            width="200" 
            align="center">
            <template #default="scope">
              {{ formatTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template #default="scope">
              <el-button 
                size="small" 
                type="primary" 
                @click="openEditStockDialog(scope.row)"
                class="edit-btn">
                编辑库存
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row.id)"
                class="delete-btn">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页控件 -->
        <div class="pagination-area">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5,10,20,50]"
            :page-size="pageSize"
            :total="tableData.length"
            layout="total, sizes, prev, pager, next, jumper"
            background
            class="pagination">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 添加图书对话框 -->
    <el-dialog 
      title="添加图书" 
      v-model="addDialogVisible" 
      width="50%"
      top="60px"
      :close-on-click-modal="false"
      custom-class="book-dialog add-dialog">
      <el-form 
        :model="addForm" 
        ref="addFormRef" 
        :rules="rules" 
        label-width="120px"
        class="dialog-form">
        <el-form-item label="图书标题" prop="title" class="dialog-form-item">
          <el-input 
            v-model="addForm.title" 
            placeholder="请输入图书标题"
            prefix-icon="el-icon-book">
          </el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author" class="dialog-form-item">
          <el-input 
            v-model="addForm.author" 
            placeholder="请输入作者"
            prefix-icon="el-icon-user">
          </el-input>
        </el-form-item>
        <el-form-item label="ISBN" prop="isbn" class="dialog-form-item">
          <el-input 
            v-model="addForm.isbn" 
            placeholder="请输入ISBN"
            prefix-icon="el-icon-barcode">
          </el-input>
        </el-form-item>
        <el-form-item label="分类" prop="category" class="dialog-form-item">
          <el-input 
            v-model="addForm.category" 
            placeholder="请输入分类"
            prefix-icon="el-icon-tags">
          </el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="stock" class="dialog-form-item">
          <el-input 
            v-model.number="addForm.stock" 
            type="number" 
            placeholder="请输入库存数量"
            prefix-icon="el-icon-inbox"
            min="0">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false" class="dialog-btn cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleAdd" class="dialog-btn confirm-btn">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑库存对话框 -->
    <el-dialog 
      title="编辑图书库存" 
      v-model="editDialogVisible" 
      width="50%"
      top="60px"
      :close-on-click-modal="false"
      custom-class="book-dialog edit-dialog">
      <el-form 
        :model="editForm" 
        ref="editFormRef" 
        :rules="editRules" 
        label-width="120px"
        class="dialog-form">
        <el-form-item label="图书ID" prop="id" class="dialog-form-item">
          <el-input v-model="editForm.id" disabled prefix-icon="el-icon-key"></el-input>
        </el-form-item>
        <el-form-item label="图书标题" prop="title" class="dialog-form-item">
          <el-input v-model="editForm.title" disabled prefix-icon="el-icon-book"></el-input>
        </el-form-item>
        <el-form-item label="当前库存" prop="stock" class="dialog-form-item">
          <el-input 
            v-model.number="editForm.stock" 
            type="number" 
            placeholder="请输入库存数量"
            prefix-icon="el-icon-inbox"
            min="0">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false" class="dialog-btn cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleUpdateStock" class="dialog-btn confirm-btn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
// 假设 axios 相关请求方法在 utils/request.js 中，需根据实际路径调整
import { post, get } from '@/utils/axios.js'

// 表格数据与分页
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])

// 查询表单
const searchForm = reactive({
  title: '',
  category: ''
})

// 添加对话框相关
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  title: '',
  author: '',
  isbn: '',
  category: '',
  stock: 0
})

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: '',
  title: '',
  stock: 0
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入图书标题', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  isbn: [
    { required: true, message: '请输入ISBN', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存数量不能为负数', trigger: 'blur' }
  ]
}

// 编辑表单验证规则
const editRules = {
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存数量不能为负数', trigger: 'blur' }
  ]
}

// 分页方法
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1 // 重置为第一页，保持分页逻辑一致性
}

function handleCurrentChange(val) {
  currentPage.value = val
}

// 获取所有图书数据
function getAllBooks() {
  get('/api/books/getAll', {}, (res) => {
    if (res.status === 1) {
      tableData.value = res.data
    } else {
      ElMessage.error('未查询到数据')
      tableData.value = []
    }
  })
}

// 搜索图书
function searchBooks() {
  if (searchForm.title) {
    // 按标题查询
    get('/api/books/getByTitle', { title: searchForm.title }, (res) => {
      handleSearchResult(res)
    })
  } else if (searchForm.category) {
    // 按分类查询
    get('/api/books/getByCategory', { category: searchForm.category }, (res) => {
      handleSearchResult(res)
    })
  } else {
    // 无查询条件时显示全部
    getAllBooks()
  }
}

// 处理搜索结果
function handleSearchResult(res) {
  if (res.status === 1) {
    tableData.value = res.data
    ElMessage.success('查询成功')
  } else {
    ElMessage.error(res.msg || '查询失败')
    tableData.value = []
  }
}

// 重置搜索
function resetSearch() {
  searchForm.title = ''
  searchForm.category = ''
  getAllBooks()
}

// 打开添加对话框
function openAddDialog() {
  // 重置表单数据
  addForm.title = ''
  addForm.author = ''
  addForm.isbn = ''
  addForm.category = ''
  addForm.stock = 0
  
  addDialogVisible.value = true
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (addFormRef.value) {
      addFormRef.value.clearValidate()
    }
  })
}

// 处理添加
function handleAdd() {
  addFormRef.value.validate((valid) => {
    if (valid) {
      post('/api/books/add', addForm, (res) => {
        if (res.status === 1) {
          ElMessage.success('添加成功')
          addDialogVisible.value = false
          getAllBooks()
        } else {
          ElMessage.error(res.msg || '添加失败')
        }
      })
    }
  })
}

// 打开编辑库存对话框
function openEditStockDialog(row) {
  // 复制行数据到编辑表单
  editForm.id = row.id
  editForm.title = row.title
  editForm.stock = row.stock
  
  editDialogVisible.value = true
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (editFormRef.value) {
      editFormRef.value.clearValidate()
    }
  })
}

// 处理库存更新
function handleUpdateStock() {
  editFormRef.value.validate((valid) => {
    if (valid) {
      post('/api/books/updateStock', {
        id: editForm.id,
        stock: editForm.stock
      }, (res) => {
        if (res.status === 1) {
          ElMessage.success('库存更新成功')
          editDialogVisible.value = false
          getAllBooks()
        } else {
          ElMessage.error(res.msg || '更新失败')
        }
      })
    }
  })
}

// 处理删除
function handleDelete(id) {
  ElMessageBox.confirm(
    `确定要删除ID为【${id}】的图书吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    get('/api/books/deleteById', { id }, (res) => {
      if (res.status === 1) {
        ElMessage.success('删除成功')
        getAllBooks()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    // 取消删除，不做额外操作
  })
}

// 表格行样式（奇偶行区分）
function tableRowClass({ rowIndex }) {
  return rowIndex % 2 === 0 ? 'table-row-even' : 'table-row-odd'
}

// 表格表头样式
function tableHeaderStyle() {
  return {
    'background-color': '#f5f7fa',
    'font-weight': '600',
    'color': '#333',
    'font-size': '14px',
    'border-bottom': '2px solid #e4e7ed'
  }
}

// 表格单元格样式
function tableCellStyle() {
  return {
    'font-size': '14px',
    'padding': '12px 0',
    'transition': 'background-color 0.2s ease'
  }
}

// 获取分类标签类型（区分颜色）
function getTagType(category) {
  const typeMap = {
    '计算机': 'primary',
    '文学': 'success',
    '历史': 'warning',
    '经济': 'info',
    '科普': 'danger',
    '艺术': 'purple'
  }
  // 匹配分类关键词返回对应类型，无匹配则用默认
  const matchKey = Object.keys(typeMap).find(key => category.includes(key))
  return matchKey ? typeMap[matchKey] : 'default'
}

// 格式化时间（处理后端返回的LocalDateTime）
function formatTime(time) {
  if (!time) return ''
  // 处理 "2024-05-20T14:30:00" 格式为 "2024-05-20 14:30:00"
  return time.replace('T', ' ')
}

// 页面加载时获取所有数据
onMounted(() => {
  getAllBooks()
})
</script>

<style scoped>
/* 全局外层容器 */
.book-manage-wrap {
  padding: 24px;
  background-color: #f8f9fa;
  min-height: 100vh;
  font-family: "Microsoft YaHei", sans-serif;
}

/* 顶部标题栏 */
.book-header {
  margin-bottom: 28px;
}

.header-inner {
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header-title {
  font-size: 22px;
  font-weight: 700;
  color: #333;
  margin: 0 0 8px 0;
}

.header-desc {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 操作区（搜索+新增） */
.book-operation {
  margin-bottom: 28px;
}

.operation-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 搜索表单区 */
.search-area {
  flex: 1;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
}

.form-item {
  margin-bottom: 0;
}

.search-input {
  width: 240px;
  border-radius: 4px;
  border-color: #dcdfe6;
  transition: all 0.3s ease;
}

.search-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-btn-group {
  display: flex;
  gap: 12px;
}

.search-btn, .reset-btn {
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.search-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.search-btn:hover {
  background-color: #337ecc;
  border-color: #337ecc;
}

.reset-btn {
  background-color: #fff;
  color: #666;
  border-color: #dcdfe6;
}

.reset-btn:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
}

/* 新增按钮区 */
.add-btn-area {
  margin-left: 20px;
}

.add-btn {
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
  background-color: #67c23a;
  border-color: #67c23a;
}

.add-btn:hover {
  background-color: #529b2e;
  border-color: #529b2e;
}

/* 表格展示区 */
.book-table {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.table-card {
  padding: 20px;
}

/* 表格头部统计 */
.table-header {
  margin-bottom: 16px;
}

.table-count {
  font-size: 14px;
  color: #666;
}

.count-num {
  color: #409eff;
  font-weight: 600;
  font-size: 15px;
}

/* 表格样式 */
.el-table {
  border-radius: 4px;
}

.el-table tr:hover > td {
  background-color: #f9fafc !important;
}

.table-row-even {
  background-color: #fafbfd;
}

.table-row-odd {
  background-color: #fff;
}

.book-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  padding: 0 8px;
}

/* 分类标签 */
.category-tag {
  padding: 4px 10px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

/* 库存状态样式 */
.stock-out {
  color: #f56c6c;
  font-weight: 600;
}

.stock-normal {
  color: #67c23a;
  font-weight: 600;
}

/* 表格操作按钮 */
.edit-btn, .delete-btn {
  margin: 0 6px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.edit-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.edit-btn:hover {
  background-color: #337ecc;
  border-color: #337ecc;
}

.delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.delete-btn:hover {
  background-color: #e64949;
  border-color: #e64949;
}

/* 分页区域 */
.pagination-area {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.pagination {
  margin: 0;
}

.el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #409eff;
  color: #fff;
}

/* 对话框样式 */
.book-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.el-dialog__header {
  background-color: #f5f7fa;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.el-dialog__body {
  max-height: 500px;
  overflow-y: auto;
  padding: 24px;
}

.dialog-form {
  width: 100%;
}

.dialog-form-item {
  margin-bottom: 20px;
}

.dialog-form-item .el-input {
  border-radius: 4px;
  border-color: #dcdfe6;
  transition: all 0.3s ease;
}

.dialog-form-item .el-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 对话框按钮 */
.dialog-btn {
  padding: 8px 20px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.cancel-btn {
  background-color: #fff;
  color: #666;
  border-color: #dcdfe6;
}

.cancel-btn:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
}

.confirm-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.confirm-btn:hover {
  background-color: #337ecc;
  border-color: #337ecc;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .search-input {
    width: 200px;
  }
}

@media (max-width: 992px) {
  .operation-card {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .add-btn-area {
    margin-left: 0;
    text-align: right;
  }
  
  .search-form {
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
    margin-bottom: 8px;
  }
}

@media (max-width: 768px) {
  .book-manage-wrap {
    padding: 12px;
  }
  
  .table-card {
    padding: 12px;
  }
  
  .el-dialog {
    width: 90% !important;
  }
}
</style>